package testProject;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.onpositive.page.pagerendering.EditLinkRenderer;
import com.onpositive.page.pagerendering.EditPageContentRenderer;
import com.onpositive.page.pagerendering.SiteContentRenderer;
import com.onpositive.page.pagerendering.interfaces.ISiteContentRenderer;
import com.onpositive.storage.managers.UnifiedContentProvider;

@SuppressWarnings("serial")
public class PageEditServlet extends HttpServlet {
	private static ISiteContentRenderer iscr = SiteContentRenderer
			.getSiteContentRenderer();
	private final static String INNERCOUNTER = "innerCount";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String reqStr = req.getRequestURI();
		// if (!isUserLoginned) {
		// } else {
		String mapped = reqStr;
		if (mapped.endsWith(EditLinkRenderer.SUFFIX)) {
			mapped = reqStr.substring(0, mapped.length()
					- EditLinkRenderer.SUFFIX.length());
		}
		byte[] content = UnifiedContentProvider
				.getContentElementAsBytes(mapped);
		String strContent = new String(content);
		String path = "";
		if (reqStr.indexOf(UnifiedContentProvider.RESOURCES_DIR) == 0) {
			path = UnifiedContentProvider.RESOURCES_DIR;
			path = "\\.\\./";
		}
		EditPageContentRenderer epcr = new EditPageContentRenderer(strContent,
				reqStr, path);
		// resp.setContentType("text/html");

		iscr.initRenderer(getServletContext());
		String c = epcr.getContent();
		((SiteContentRenderer) iscr).render(resp, c, mapped, true, true);
		// }

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String reqStr = req.getRequestURI();
		if (reqStr.endsWith(EditLinkRenderer.SUFFIX)) {
			reqStr = reqStr.substring(0, reqStr.length()
					- EditLinkRenderer.SUFFIX.length());
		}

		String commitContent = req
				.getParameter(EditPageContentRenderer.FIELD_WITH_CONTENT_NAME);
		UnifiedContentProvider.updateContentElement(reqStr, commitContent
				.getBytes());
		if (reqStr.indexOf(UnifiedContentProvider.RESOURCES_DIR) != -1) {
			reqStr = "/index";
		}
		resp.sendRedirect(reqStr);

	}
}
